package com.lkd.handler;

import com.lkd.business.MsgHandler;
import com.lkd.common.VMSystem;
import com.lkd.config.TopicConfig;
import com.lkd.contract.StatusInfo;
import com.lkd.contract.VmStatusContract;
import com.lkd.emq.Topic;
import com.lkd.entity.TaskEntity;
import com.lkd.feign.VMService;
import com.lkd.http.vo.TaskViewModel;
import com.lkd.service.TaskService;
import com.lkd.utils.JsonUtil;
import com.lkd.vo.VmVO;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import java.io.IOException;
import java.util.List;

@Component
@Topic(TopicConfig.VMS_STATUS_TOPIC)
@Slf4j
public class VmsStatusMsgHandler implements MsgHandler {

    @Autowired
    private TaskService taskService;
    @Autowired
    private VMService vmService;

    @Override
    public void process(String jsonMsg) throws IOException {
        if(StringUtils.isEmpty(jsonMsg)){
            log.error(TopicConfig.VMS_STATUS_TOPIC + "接收到消息内容为空!");
            return;
        }
        //1.接收消息
        VmStatusContract contract = JsonUtil.getByJson(jsonMsg, VmStatusContract.class);
        //2.校验消息
        String innerCode = contract.getInnerCode();
        List<StatusInfo> statusInfo = contract.getStatusInfo();
        if(StringUtils.isEmpty(innerCode) || CollectionUtils.isEmpty(statusInfo)){
            log.error(TopicConfig.VMS_STATUS_TOPIC + "消息内容不完整" + jsonMsg);
            return;
        }

        //3.判断售货机是否故障
        boolean b = statusInfo.stream().anyMatch(data -> !data.isStatus());
        if(!b){
            //没有损坏直接结束
            return;
        }

        //远程调用售货机信息
        VmVO vmInfo = vmService.getVMInfo(innerCode);
        if(vmInfo == null){
            log.error("售货机上报状态信息，编码有误"+innerCode);
            return;
        }

        //4.创建工单参数对象,复用create创建工单方法
        TaskViewModel model = new TaskViewModel();
        model.setAssignorId(0);
        model.setInnerCode(innerCode);
        model.setCreateType(VMSystem.TASK_CREATE_TYPE_AUTO);
        model.setProductType(VMSystem.TASK_TYPE_REPAIR);

        Integer userId = taskService.getLeastTaskCountUser(vmInfo.getRegionId(), true);
        model.setUserId(userId);
        model.setDesc(jsonMsg);
        taskService.create(model);

    }
}
